<?php

namespace App\Service\UserCenter;

use App\Constants\ErrorCode;
use App\Helpers\ConfigUtil;
use App\Model\Service\CacheService;
use App\Model\Setting\SettingUserLevel;
use App\Model\UserProfile;
use App\Service\BaseService;

/**
 * 设置我的收费
 */
class SetMycoinService extends BaseService
{
    public function handle()
    {
        $isNewVersion = $this->curVersion >= '1.0.0';
        $userId = $this->getUserId();
        $myCoinSet = $this->request->input('my_coin_set', 0);
        //收费类型：0-默认语音，1-视频，2-文字
        $coinType = $this->request->input('coin_type', 0);

        //功能维护
//        $profile = UserProfile::getProfile($userId);
//        if (!$profile || !UserProfile::checkRoleHost($profile->role)) {
//            return $this->setError(ErrorCode::SET_COIN_ERROR, '非实名认证用户，无法设置～');
//        }

        $profile = UserProfile::getProfile($userId);
        if (!$profile || !UserProfile::checkAvatarVrfied($userId, $profile)) {
            return $this->setError(ErrorCode::SET_COIN_ERROR, '非真人认证用户，无法设置～');
        }

        $myCoinSet = floatval($myCoinSet);
        // $profile = UserProfile::getProfile($userId);
        //设置
        switch ($coinType) {
                //语音
            case 0:
                $coinField = 'coin_setting';
                break;
                //视频
            case 1:
                $coinField = 'video_coin_setting';
                break;
                //文字
            case 2:
                $coinField = 'chat_coin_setting';
                break;
        }
        //检测是否满足条件
        if ($isNewVersion) {
            $check = SettingUserLevel::checkCoinSet($myCoinSet, $profile->charm_value, $coinField);
        } else {
            $check = $this->checkCoinSet($myCoinSet, $profile->charm_value, $coinType);
        }

        if ($check['errcode']) {
            log_user_result($userId, "CoinSet:{$myCoinSet}==Value:{$profile->charm_value}");
            return $this->setError($check['errcode'], $check['errmsg']);
        }

        UserProfile::updateInfo($userId, [$coinField => $myCoinSet]);
        return ['result' => 1];
    }

    /**
     * 查询收费设置
     */
    function checkCoinSet($myCoinSet, $myCharm = 0, $coinType)
    {
        $settings = ConfigUtil::getCoinSetting($coinType);
        foreach ($settings as $coinSet) {
            if ($coinSet['coin'] != $myCoinSet) continue;
            if ($myCharm < $coinSet['charm_limit']) {
                return ['errcode' => ErrorCode::SET_COIN_ERROR, 'errmsg' => '魅力值不满足条件！'];
            }
            return ['errcode' => 0];
        }
        return ['errcode' => ErrorCode::SET_COIN_ERROR, 'errmsg' => '没有该设置！'];
    }
}
